package com.shfl.task.component;

import com.shfl.task.exception.ApiTaskException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Component
public class RemoteComponent {

    @Autowired
    @Qualifier("sslRestTemplate")
    private RestTemplate restTemplate;

    public void send(SendInfo info) throws Exception {
        createRequest(info, Object.class);
    }

    private <T> T createRequest(SendInfo info, Class<T> c) throws Exception {
        String sendUrl = "http://".concat(info.getSendUrl());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //用HttpEntity封装整个请求报文
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(info.getObjectMap(), headers);
        T result;
        try {
            result = restTemplate.postForObject(sendUrl, request, c);
        } catch (ResourceAccessException e) {
            throw new ApiTaskException("9114");
        }
        return result;
    }
}